package com.supercell.misc.util;

import com.supercell.entity.Department;
import com.supercell.entity.GenericEntity;
import com.supercell.entity.Person;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by WUJO2 on 7/16/2016.
 */
public class EntityParser {
    private EntityParser() {
    }

    public static GenericEntity parse(String textRepresentation, DateFormat birthDateFormat, Class parsedClass) throws ParseException {
        Pattern pattern = Pattern.compile("([^,]+?):([^:,]+)");
        Matcher matcher = pattern.matcher(textRepresentation);
        Map<String, String> parsedKeyValuePairs = new HashMap<>();
        GenericEntity parsedEntity;
        while (matcher.find()) {
            parsedKeyValuePairs.put(matcher.group(1), matcher.group(2));
        }
        if (parsedClass.getName().equals(Person.class.getName())) {
            Person person = new Person();
            for (String key : parsedKeyValuePairs.keySet()) {
                if (key.equalsIgnoreCase(Person.ID)) {
                    person.setId(Integer.valueOf(parsedKeyValuePairs.get(key)));
                } else if (key.equalsIgnoreCase(Person.CLIENT_SIDE_DUMMY_NAME)) {
                    person.setName(parsedKeyValuePairs.get(key));
                } else if (key.equalsIgnoreCase(Person.BIRTHDAY)) {
                    person.setBirthday(birthDateFormat.parse(parsedKeyValuePairs.get(key)));
                } else if (key.equalsIgnoreCase(Person.CLIENT_SIDE_DUMMY_TELEPHONE)) {
                    person.setTelephone(parsedKeyValuePairs.get(key));
                } else if (key.equalsIgnoreCase(Person.CLIENT_SIDE_DUMMY_DEPARTMENT_ID)) {
                    person.setDepartmentID(Integer.valueOf(parsedKeyValuePairs.get(key)));
                } else if (key.equalsIgnoreCase(Person.SALARY)) {
                    person.setSalary(Integer.valueOf(parsedKeyValuePairs.get(key)));
                }
            }
            parsedEntity = person;
        } else {
            Department department = new Department();
            for (String key : parsedKeyValuePairs.keySet()) {
                if (key.equalsIgnoreCase(Department.ID)) {
                    department.setId(Integer.valueOf(parsedKeyValuePairs.get(key)));
                } else if (key.equalsIgnoreCase(Department.CLIENT_SIDE_DUMMY_DEPARTMENT_NAME)) {
                    department.setDepartmentName(parsedKeyValuePairs.get(key));
                } else if (key.equalsIgnoreCase(Department.CITY)) {
                    department.setCity(parsedKeyValuePairs.get(key));
                }
            }
            parsedEntity = department;
        }
        return parsedEntity;
    }
}
